<template>
  <el-container>
    <!--查询条件开始-->
    <el-header height="1">
      <el-button type="success" size="small" @click="showDialog('add')">新增</el-button>
    </el-header>
    <!--查询条件结束-->
    <!--列表开始-->
    <el-main>
      <table-pagination
        :table-data="table.assest.tableData"
        :table-header-config="table.tableHeaderConfig"
        :total="table.assest.total"
        :filter-data="table.filterData"
        :dict-data="dict"
        :page-size="table.assest.limit"
        :now-page="table.assest.nowPage"
        :operation-config="table.operationConfig"
        @current-change="currentChange"
      />
    </el-main>
    <!--列表结束-->
    <!--弹出框开始-->
    <el-dialog :title="editModStr" :visible.sync="parmsValue.updateOpen" :before-close="handleClose">
      <el-form ref="updateForm" size="small" :model="parmsValue.update" label-width="160px" :rules="form.rules" class="middle-form">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="settle_date" label="交易日期">
              <el-date-picker v-model="parmsValue.update.settle_date" format="yyyy-MM-dd" value-format="yyyyMMdd" :clearable="true" :disabled="detailMod || updateMod" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="t8_sys_portfol_id" label="产品组合">
              <el-select v-model="parmsValue.update.t8_sys_portfol_id" :clearable="true" :disabled="detailMod || updateMod" @change="getProd">
                <el-option v-for="(item,index) in dict.M8000EQPORT" :key="index" :value="item.value" :label="item.value+'-'+item.text" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="prod_code" label="理财产品">
              <el-select v-model="parmsValue.update.prod_code" :clearable="true" :disabled="detailMod || updateMod" @change="getProdInfo">
                <el-option v-for="(item,index) in dict.M834SCSP002EQ001" :key="index" :value="item.value" :label="item.value+'-'+item.text" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="prodbalance" label="产品余额(元)">
              <el-input v-model="parmsValue.update.prodbalance" :clearable="true" :disabled="detailMod || updateMod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="busdirection" label="交易方向">
              <el-select v-model="parmsValue.update.busdirection" :clearable="true" :disabled="detailMod || updateMod">
                <el-option v-for="(item,index) in dict.busdirection" :key="index" :value="index" :label="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="isassdept" label="资产/负债">
              <el-select v-model="parmsValue.update.isassdept" :clearable="true" :disabled="detailMod || updateMod">
                <el-option v-for="(item,index) in dict.isassdept" :key="index" :value="index" :label="index+'-'+item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="ftool_code" label="资产代码">
              <el-input v-model="parmsValue.update.ftool_code" :clearable="true" :disabled="detailMod || updateMod" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="ftool_name" label="资产名称">
              <el-input v-model="parmsValue.update.ftool_name" :clearable="true" :disabled="detailMod || updateMod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="income_rate" label="收益率(%)">
              <el-input v-model="parmsValue.update.income_rate" :clearable="true" :disabled="detailMod" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="payinterest_freq" label="付息频率">
              <el-select v-model="parmsValue.update.payinterest_freq" :clearable="true" :disabled="detailMod">
                <el-option v-for="(item,index) in dict.t8_pay_newfreq" :key="index" :value="index" :label="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="startinterest_date" label="起息日">
              <el-date-picker v-model="parmsValue.update.startinterest_date" format="yyyy-MM-dd" value-format="yyyyMMdd" :clearable="true" :disabled="detailMod" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="endinterest_date" label="到期日">
              <el-date-picker v-model="parmsValue.update.endinterest_date" format="yyyy-MM-dd" value-format="yyyyMMdd" :clearable="true" :disabled="detailMod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="basedays" label="计息基数">
              <el-select v-model="parmsValue.update.basedays" :clearable="true" :disabled="detailMod">
                <el-option v-for="(value,key,index) in dict.t8_intr_base" :key="index" :value="key+''" :label="value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="maturegrossamount" label="交易金额(元)">
              <el-input v-model="parmsValue.update.maturegrossamount" :clearable="true" :disabled="detailMod" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" size="small" @click="closeDialog">取消</el-button>
        <el-button type="success" size="small" @click="update">确定</el-button>
      </div>
    </el-dialog>
    <!--弹出框结束-->
  </el-container>
</template>

<script>
  import { formItems } from '@/utils/formItems'
  import * as kk from '@/utils/k-utils'
  import { k_load_exeid } from '@/utils/k-utils'
  import request from '@/utils/request'
  import axios from 'axios'

  export default {
    data() {
      return {
        dict: {
          isassdept: { '1': '资产', '2': '负债' },
          M834SCSP002EQ001: {},
          M8000EQPORT: {},
          t8_pay_newfreq: {},
          t8_intr_base: {},
          busdirection: {}
        },
        table: {
          filterData: {
            day: [formItems.startInterestDate.prop, formItems.endInterestDate.prop],
            money: [formItems.matureGrossAmount.prop],
            delimiter: 'ch'
          },
          assest: {
            tableData: [],
            exeid: 'M834SCSP002EQ003',
            total: 100,
            limit: 10,
            nowPage: 1
          },
          tableHeaderConfig: [
            formItems.portName, formItems.prodCode, formItems.ftoolCode, formItems.startInterestDate, formItems.endInterestDate,
            formItems.incomeRate, formItems.busDirection, formItems.matureGrossAmount, formItems.baseDays
          ],
          operationConfig: {
            fixed: 'left',
            width: 220,
            operationButton: [
              { value: '修改', func: (row) => this.showDialog('update', row) },
              { value: '删除', func: (row) => this.deleteAssest(row) },
              { value: '详情', func: (row) => this.showDialog('detail', row) }
            ]
          }
        },
        form: {
          rules: {
            settle_date: [{ required: true, message: '交易日期必选', trigger: 'change' }],
            t8_sys_portfol_id: [{ required: true, message: '产品组合必选', trigger: 'change' }],
            prod_code: [{ required: true, message: '理财产品必选', trigger: 'change' }],
            prodbalance: [{ required: true, message: '产品余额必填', trigger: 'change' }],
            busdirection: [{ required: true, message: '交易方向必选', trigger: 'change' }],
            isassdept: [{ required: true, message: '资产/负债必选', trigger: 'change' }],
            ftool_code: [{ required: true, message: '资产代码必填', trigger: 'change' }],
            ftool_name: [{ required: true, message: '资产名称必填', trigger: 'change' }],
            income_rate: [{ required: true, message: '收益率必填', trigger: 'change' }],
            payinterest_freq: [{ required: true, message: '付息频率必选', trigger: 'change' }],
            startinterest_date: [{ required: true, message: '起息日必选', trigger: 'change' }],
            endinterest_date: [{ required: true, message: '到期日必选', trigger: 'change' }],
            basedays: [{ required: true, message: '计息基数必选', trigger: 'change' }],
            maturegrossamount: [{ required: true, message: '交易金额必填', trigger: 'change' }]
          }
        },
        parmsValue: {
          // 查询字段值
          updateOpen: false,
          editMod: 'update',
          update: {
            mdfy: 0,
            prodmoney: '',
            settle_date: '',
            t8_sys_portfol_id: '',
            prod_code: '',
            prodbalance: '',
            busdirection: '',
            isassdept: '',
            ftool_code: '',
            ftool_name: '',
            income_rate: '',
            payinterest_freq: '',
            startinterest_date: '',
            endinterest_date: '',
            basedays: '',
            maturegrossamount: ''
          }
        }
      }
    },
    computed: {
      editModStr() {
        switch (this.parmsValue.editMod) {
        case 'update':
          return '修改情景资产信息'
        case 'add':
          return '新增情景资产信息'
        case 'detail':
        default:
          return '情景资产信息详情'
        }
      },
      updateMod() {
        return this.parmsValue.editMod === 'update'
      },
      detailMod() {
        return this.parmsValue.editMod === 'detail'
      },
      addMod() {
        return this.parmsValue.editMod === 'add'
      }
    },
    // 生命周期开始
    // 生命周期结束
    methods: {
      currentChange(index) {
        this.table.assest.nowPage = index
        this.loadTable()
      },
      init() {
        const dictReq = []
        const dicts = ['t8_pay_newfreq', 't8_intr_base', 't8_direction']
        dicts.forEach(key => dictReq.push(request({ url: 'system/base/dict/' + key + '.json', method: 'post', loading: true })))
        axios.all(dictReq).then(axios.spread((t8_pay_newfreq, t8_intr_base, busdirection) => {
          this.dict['t8_pay_newfreq'] = t8_pay_newfreq
          this.dict['t8_intr_base'] = t8_intr_base
          this.dict['busdirection'] = busdirection

          // 加载exeid数据字典
          const exeidReq = []
          const exeids = [{ service: formItems.DATA, params: { exeid: 'M8000EQPORT' }}, { service: formItems.DATA, params: { exeid: 'M834SCSP002EQ001' }}]
          exeids.forEach(item => exeidReq.push(request({
            url: '/' + item.service + '/base/comn-query.json', method: 'post', loading: true, params: item.params
          })))
          axios.all(exeidReq).then(axios.spread((...items) => {
            for (let i = 0; i < exeids.length; i++) {
              if (exeids[i].dict) {
                this.dict[exeids[i].dict] = items[i].rows
              } else {
                this.dict[exeids[i].params.exeid] = items[i].rows
              }
            }

            // 正式加载表格数据
            this.loadTable()
          }))
        }))
      },
      loadTable() {
        kk.k_load_table(this, 'assest', formItems.DATA)
      },
      showDialog(editMod, params = {}) {
        switch (editMod) {
        case 'add':
          this.parmsValue.editMod = 'add'
          this.parmsValue.updateOpen = true
          break
        case 'update':
          this.parmsValue.editMod = 'update'
          this.parmsValue.updateOpen = true
          this.$nextTick(() => {
            Object.assign(this.parmsValue.update, params)
          })
          break
        case 'detail':
          this.parmsValue.editMod = 'detail'
          this.parmsValue.updateOpen = true
          this.$nextTick(() => {
            Object.assign(this.parmsValue.update, params)
          })
          break
        default:
        }
      },
      handleClose(done) {
        this.resetFields('updateForm')
        done()
      },
      closeDialog() {
        this.parmsValue.updateOpen = false
        this.resetFields('updateForm')
      },
      update() {
        if (this.parmsValue.update.isassdept === '1' && this.parmsValue.update.busdirection === '-1') {
        }

        // 做资产卖出的时候先进行持仓份额判断是否足够
        if (this.parmsValue.update.busdirection === '1') {
        }

        this.parmsValue.update.mdfy = this.updateMod ? 1 : 0
        this.$refs['updateForm'].validate(valid => {
          kk.k_load_url(formItems.DATA, '/sceneasset.action', { param: '{[json]}' + JSON.stringify(this.parmsValue.update) })
            .then(resp => {
              if (resp.success) {
                this.closeDialog()
                this.loadTable()
              }
            })
        })
      },
      deleteAssest(params) {

      },
      resetFields(form) {
        this.$refs[form].resetFields()
      },
      getProdInfo() {
        let isExit = false

        const callback = () => {
          if (isExit && this.parmsValue.update.prod_code !== '' && this.parmsValue.update.prod_code !== null) {
            k_load_exeid(formItems.DATA, 'M834SCSP002EQ002', {
              prod_code: this.parmsValue.update.prod_code,
              settle_date: this.parmsValue.update.settle_date
            }).then(resp => {
              if (resp.rows.length > 0) {
                this.parmsValue.update.prodmoney = resp.rows[0].prodmoney
              }
            })
          } else {
            this.parmsValue.update.prod_code = ''
            this.parmsValue.update.prodbalance = 0
          }
        }

        k_load_exeid(formItems.DATA, 'M834SCSP002EQ001', {
          prod_code: this.parmsValue.update.prod_code,
          settle_date: this.parmsValue.update.settle_date,
          t8_sys_portfol_id: this.parmsValue.update.t8_sys_portfol_id
        }).then(resp => {
          if (resp.rows.length > 0) {
            isExit = true
          }
          callback()
        })
      },
      getProd() {
        this.parmsValue.update.prod_code = ''
        this.parmsValue.update.prodmoney = 0

        kk.k_load_exeid(formItems.DATA, 'M834SCSP002EQ001', {
          t8_sys_portfol_id: this.parmsValue.update.t8_sys_portfol_id,
          settle_date: this.parmsValue.update.settle_date
        }).then(resp => {
          this.dict['M834SCSP002EQ001'] = resp.rows
        })
      }
    }
  }
</script>
